
//Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }
    public int dfs(TreeNode root, int num){
        num = num * 10 + root.val;
        if(root.left == null && root.right == null){
            return num;
        }
        int left = 0;
        int right = 0;
        if(root.left != null){
            left = dfs(root.left, num);
            //System.out.println(left);
        }
        if(root.right != null){
            right = dfs(root.right, num);
            //System.out.println(right);
        }
        return left + right;
    }
}